package com.xapp.activity.mainActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.xapp.R;
import com.xapp.activity.errorActivity.NetWorkAvtivity;
import com.xapp.activity.mainActivity.presenter.MainPresenterCompl;
import com.xapp.baseContent.BaseActivity;

import com.xapp.utils.BaiduLocationUtils;
import com.xapp.utils.ConstantUils;
import com.xapp.utils.GPSUtils;
import com.xapp.utils.ImageUtils;
import com.xapp.utils.PopWindowUtils;
import com.xapp.utils.RegisterFucUtils;
import com.xapp.utils.SharedPreferencesUtils;
import com.xapp.yhjsBirdge.BridgeWebView;
import com.xapp.yhjsBirdge.BridgeWebViewClient;
import com.xapp.yhjsBirdge.DefaultHandler;

import org.greenrobot.eventbus.EventBus;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MainActivity extends BaseActivity {

    private final String TAG = MainActivity.class.getSimpleName();
    private String mWevViewURL = ConstantUils.defaultURL;
    public BridgeWebView mVebView;
    public MainPresenterCompl mMainPresenterCompl;
    public RegisterFucUtils mRegisterFucUtils;
    private MyMainHandler myMainHandler;
    private LinearLayout mLoadView;
    public String mPhone;
    public String mImagePickerJson;
    public String imageFrontName, imageBackName, imageFaceName, idCardOwnerTip;
    private Boolean isShowFirst = false;
    private ConstraintLayout mMainLayout;
    private int permissionDeninedId = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_webview);
        XXPermissions.with(this)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
                            // 所有权限获取成功
                        } else {
                            // 部分权限获取成功
                        }
                    }
                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (quick) {
                            // 永久拒绝授权　
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.gotoPermissionSettings(MainActivity.this);
                        } else {
                            // 获取权限失败
                        }
                    }
        });

        mMainLayout = (ConstraintLayout)findViewById(R.id.main_layout);
        initUtils();
        initWebView();
        mVebView.loadUrl(mWevViewURL);
    }

    private void initUtils() {
        String sdCardDir = this.getFilesDir().getAbsolutePath() + ConstantUils.fileSvaeDir;
        SharedPreferencesUtils.setParam(mContext, "checLoaction", "0");//每次启动获取定位
        myMainHandler = new MyMainHandler(this, new MyMainHandler.SetPopListener() {
            @Override
            public void click() {
                PopWindowUtils.showPopUpWindow(MainActivity.this, mMainLayout, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        permissionDeninedId = 1;
                        mMainPresenterCompl.checkPermissionHandler(ConstantUils.GET_EXTERNAL_STORAGE_REQUEST_CODE, 1023, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        permissionDeninedId = 2;
                        mMainPresenterCompl.checkPermissionHandler(ConstantUils.GET_EXTERNAL_STORAGE_REQUEST_CODE, 1017, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                });
            }
        });
        mMainPresenterCompl = new MainPresenterCompl(mContext, sdCardDir, myMainHandler);
        mRegisterFucUtils = new RegisterFucUtils(mContext, myMainHandler);
    }
    private void initWebView() {
        mLoadView = (LinearLayout) findViewById(R.id.loading_view);
        mVebView = (BridgeWebView) findViewById(R.id.webview);
        mVebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置 WebView 的缓存模式
        mVebView.getSettings().setJavaScriptEnabled(true);
        mVebView.getSettings().setTextZoom(100);
        mVebView.setDefaultHandler(new DefaultHandler());
        //启用数据库
        mVebView.getSettings().setDatabaseEnabled(true);
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //启用地理定位
        mVebView.getSettings().setGeolocationEnabled(true);
        //设置定位的数据库路径
        mVebView.getSettings().setGeolocationDatabasePath(dir);
        //最重要的方法，一定要设置，这就是出不来的主要原因
        mVebView.getSettings().setDomStorageEnabled(true);
        mVebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
              GeolocationPermissions.Callback callback) {
                 callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });

        mVebView.setWebViewClient(new BridgeWebViewClient(mVebView) {

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                handler.proceed();//忽略SSL证书错误，继续执行
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!isShowFirst) {
                    isShowFirst = true;
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            mLoadView.setVisibility(View.GONE);
                        }
                    };
                    myMainHandler.postDelayed(runnable, 200);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                // 断网或者网络连接超时
                if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_CONNECT || errorCode == ERROR_TIMEOUT) {
                    //显示无网络页面
                    showErrorNetWork();
                }
            }
        });
        //注册JS调用原生的方法
        registerJSFunction();
    }

    //显示无网络页面
    private void showErrorNetWork() {
        mVebView.loadUrl("about:blank"); // 避免出现默认的错误界面
        Intent errorIntent = new Intent(mContext, NetWorkAvtivity.class);
        this.startActivityForResult(errorIntent, ConstantUils.OPEN_ERRORCTIVITY_CODE);
    }



    //打开本地浏览器
    public void openLocalBrowser(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }


    /*
     * 注册JS方法
     * */
    private void registerJSFunction() {
        mRegisterFucUtils.registerJSFunction(mVebView, ConstantUils.JS_FUNCTION_OPEN_Browser, 10002);
        mRegisterFucUtils.registerJSFunction(mVebView, ConstantUils.JS_FUNCTION_OPEN_UVCCAMERA, 10003);
        mRegisterFucUtils.registerJSFunction(mVebView, ConstantUils.JS_FUNCTION_LOCATION_FLAG, 10004);
        mRegisterFucUtils.registerJSFunction(mVebView, ConstantUils.JS_FUNCTION_UPDATE_IMAGE_FLAG, 1018);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String jsCallBackKey = "";//JS回调的Key
        JSONObject jsonObject = new JSONObject();//返回参数
        Uri mUri;
        String newPath;
        String imageBase64;
        switch (requestCode) {
            case ConstantUils.OPEN_UVCCAMERA:
                if( data != null) {
                    String tpPath = data.getStringExtra("path");

                    if(tpPath != null){
                        imageBase64 = ImageUtils.bitmapToBase64(tpPath);
                        try {
                            jsonObject.put("status", "1000");
                            JSONObject ptImageJson = new JSONObject();
                            ptImageJson.put("path", tpPath);
                            ptImageJson.put("base64", imageBase64);
                            ptImageJson.put("original", "file://" + tpPath);
                            jsonObject.put("data", ptImageJson);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else {
                        try {
                            jsonObject.put("status", "9999");
                            jsonObject.put("data", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }else {
                    try {
                        jsonObject.put("status", "9999");
                        jsonObject.put("data", "");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                jsCallBackKey = ConstantUils.JS_FUNCTION_OPEN_UVCCAMERA;
                break;
            case ConstantUils.FILE_SELECT_BY_ALBUM_CODE://选择本地图片
                if (data != null) {
                    mUri = data.getData();
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(mUri, proj, null, null, null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                            try {
                                JSONObject imageJson = new JSONObject(mImagePickerJson);
                                newPath = ImageUtils.bitmapToSmall(path, imageJson.getString("imageSize"), imageJson.getString("imageName"));

                                if ("".equals(newPath)) {
                                    jsonObject.put("status", "9999");
                                    jsonObject.put("data", "");
                                } else {
                                    imageBase64 = ImageUtils.bitmapToBase64(newPath);
                                    jsonObject.put("status", "1000");
                                    JSONObject jsonData = new JSONObject();
                                    jsonData.put("path", newPath);
                                    jsonData.put("base64", imageBase64);
                                    jsonData.put("original", "file://" + path);
                                    jsonObject.put("data", jsonData);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    } else {
                        try {
                            jsonObject.put("status", "9999");
                            jsonObject.put("data", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    try {
                        jsonObject.put("status", "4001");
                        jsonObject.put("data", "");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                jsCallBackKey = ConstantUils.JS_FUNCTION_GET_PHOTO_FLAG;
                break;
            case ConstantUils.FILE_SELECT_BY_CAMERA_CODE://拍照图片
                if (resultCode == RESULT_OK) {
                    try {
                        JSONObject imageJson = new JSONObject(mImagePickerJson);
                        newPath = ImageUtils.bitmapToSmall(ImageUtils.imagePath, imageJson.getString("imageSize"), imageJson.getString("imageName"));
                        if ("".equals(newPath)) {
                            jsonObject.put("status", "9999");
                            jsonObject.put("data", "");
                        } else {

                            imageBase64 = ImageUtils.bitmapToBase64(newPath);
                            jsonObject.put("status", "1000");
                            JSONObject jsonData = new JSONObject();
                            jsonData.put("original", "file://" + ImageUtils.imagePath);
                            jsonData.put("path", newPath);
                            jsonData.put("base64", imageBase64);
                            jsonObject.put("data", jsonData);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        jsonObject.put("status", "4001");
                        jsonObject.put("data", "");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                jsCallBackKey = ConstantUils.JS_FUNCTION_GET_PHOTO_FLAG;
                break;
            case ConstantUils.OPEN_ERRORCTIVITY_CODE://刷新WebView显示页面
                mVebView.loadUrl(mWevViewURL);
                break;
            case ConstantUils.OPEN_WEBACTIVITY_CODE://注入JS
                if (data != null) {
                    String isRefresh = data.getStringExtra("isRefresh");
                    registerJSForRefresh(isRefresh);
                }
                break;

            default:
                ErrorResultToReturn("未知结果");
                break;
        }
        if (!"".equals(jsCallBackKey)) {
            mMainPresenterCompl.callBackHandler(jsCallBackKey, jsonObject.toString());
        }
    }

    public void registerJSForRefresh(String isRefresh) {
        if ("1".equals(isRefresh)) {
            mVebView.loadUrl("javascript:YHAuthorize.registerEvent('viewWillShow', {})");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        String jsCallBackKey = "";//JS回调的Key
        JSONObject resultJson = new JSONObject();//返回参数
        Message message = new Message();
        if (permissions.length <= 0) {
            return;
        }
        Log.i(TAG, "当前检测的权限：" + permissions[0]);
        switch (requestCode) {
            case ConstantUils.OPEN_CONTACTS_REQUEST_CODE://获取联系人权限（打开联系人）
                message.what = 1003;
                jsCallBackKey = ConstantUils.JS_FUNCTION_CONTACTUI_FLAG;
                break;
            case ConstantUils.READ_CONTACTS_REQUEST_CODE://获取联系人权限（获取通讯录信息）
                message.what = 1004;
                jsCallBackKey = ConstantUils.JS_FUNCTION_CONTACTS_FLAG;
                break;
            case ConstantUils.ACCESS_COARSE_LOCATION_REQUEST_CODE://获取定位权限
                SharedPreferencesUtils.setParam(mContext, "checLoaction", "1");//标记检查过
                message.what = 1002;
                jsCallBackKey = ConstantUils.JS_FUNCTION_LOCATION_FLAG;
                break;
            case ConstantUils.READ_PHONE_STATE_REQUEST_CODE://获取手机状态
                message.what = 1005;
                //TODO 没有拒绝的处理
                break;
            case ConstantUils.GET_SMS_REQUEST_CODE:////获取短信记录
                message.what = 1014;
                jsCallBackKey = ConstantUils.JS_FUNCTION_SMS_FLAG;
                break;
            case ConstantUils.GET_EXTERNAL_STORAGE_REQUEST_CODE://获取外部存储
                JSONObject imageJson;
                try {
                    imageJson = new JSONObject(mImagePickerJson);
                    //打开相册
                    message.what = 1017;
                    if (imageJson.has("type")) {
                        String type = imageJson.getString("type");
                        if ("1".equals(type)) {
                            //申请相机权限
                            message.what = 1023;
                        }
                    }
                    if (permissionDeninedId == 1) {
                        resultJson.put("type", permissionDeninedId + "");
                    } else {
                        resultJson.put("type", "2");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                jsCallBackKey = ConstantUils.JS_FUNCTION_GET_PHOTO_FLAG;
                break;
            case ConstantUils.GET_CALL_PHONE_REQUEST_CODE://获取电话
                message.what = 1021;
                jsCallBackKey = ConstantUils.JS_FUNCTION_CALL_FLAG;
                break;
            case ConstantUils.GET_CAMERA_REQUEST_CODE://获取相机
                message.what = 1024;
                try {
                    resultJson.put("type", "1");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                jsCallBackKey = ConstantUils.JS_FUNCTION_GET_PHOTO_FLAG;
                break;
        }
        //返回结果
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            myMainHandler.sendMessage(message);
        } else {
            try {
                resultJson.put("status", "3001");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (!"".equals(jsCallBackKey)) {
                mMainPresenterCompl.callBackHandler(jsCallBackKey, resultJson.toString());
            }

        }
    }

    /**
     * 身份证扫描返回数据解析
     *
     * @param data data
     * @return JSONObject
     */
    private JSONObject initCallBackJson(Intent data) {
        byte[] imageBytesFront;
        byte[] imageBytesBack;
        boolean result;
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    /**
     * 身份证 正面 扫描返回数据解析
     */
    private JSONObject initFrontCallBackJson(Intent data) {
        byte[] imageBytesFront;
        boolean result;
        JSONObject jsonObject = new JSONObject();

        return jsonObject;
    }

    /**
     * 身份证数据分装
     */
    private JSONObject iDCardResultToReturn() {
        JSONObject resultJson = new JSONObject();


        return resultJson;
    }

    /**
     * 错误数据分装
     *
     * @return JSONObject
     */
    private JSONObject ErrorResultToReturn(String message) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("status", "4001");
            jsonObject.put("message", message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //返回键监听
    long firstime = 0;
    @Override
    public void onBackPressed() {
        if(mVebView.canGoBack()){
            mVebView.goBack();
        }else {
            long secondtime = System.currentTimeMillis();
            if (secondtime - firstime > 2000) {
                Toast.makeText(mContext, "再次点击退出程序", Toast.LENGTH_SHORT).show();
                firstime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mVebView != null) {
            mVebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mVebView.clearHistory();
            mVebView.destroy();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    //close activity
    public void closeActivity(String data) {
        String isRefresh = "-1";
        this.finish();
        if (data == null || "".equals(data)) {
            return;
        }
        try {
            Intent closeIntent = new Intent();
            JSONObject jsonObject = new JSONObject(data);
            if (jsonObject.has("isRefresh")) {
                isRefresh = jsonObject.getString("isRefresh");
            }
            closeIntent.putExtra("isRefresh", isRefresh);
            setResult(2001, closeIntent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void getLocation(){
        if( !GPSUtils.getInstance(this).isLocationProviderEnabled()){
            Toast.makeText(MainActivity.this,"请先开启gps定位",Toast.LENGTH_LONG).show();
            return;
        }
        BDLocation bdLocation = BaiduLocationUtils.getInstance(this).getLocation();
        JSONObject jsonObject = new JSONObject();
        if(null != bdLocation){
            try {
                jsonObject.put("status", "1000");
                JSONObject resultJson = new JSONObject();
                resultJson.put("latitude", bdLocation.getLatitude());
                resultJson.put("Longitude", bdLocation.getLongitude());
                resultJson.put("locationType", "baidu");
                jsonObject.put("data",resultJson);
                mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
            } catch (JSONException e) {
                Log.e(TAG, "百度经纬度: " + e.getMessage());
            }
            return;
        }else {
            Location mLocation = GPSUtils.getInstance(this).getLocation();
            if(null != mLocation){
                try{
                    jsonObject.put("status", "1000");
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("latitude", mLocation.getLatitude());
                    resultJson.put("Longitude", mLocation.getLongitude());
                    resultJson.put("locationType", "GPS");
                    jsonObject.put("data",resultJson);
                    mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
                }catch (JSONException e){
                    Log.e(TAG, "GPS经纬度: " + e.getMessage());
                }
            }else {
                try {
                    jsonObject.put("status", "9999");
                    jsonObject.put("message", "获取定位失败，请稍后再试");
                    mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return;
            }
        }

    }

    public void getGps() {
        if( !GPSUtils.getInstance(this).isLocationProviderEnabled()){
            Toast.makeText(MainActivity.this,"请先开启gps定位",Toast.LENGTH_LONG).show();
            return;
        }
        JSONObject jsonObject = new JSONObject();
        Location mLocation = GPSUtils.getInstance(this).getLocation();
        if(mLocation == null){
            try {
                jsonObject.put("status", "9999");
                jsonObject.put("message", "获取定位失败，请稍后再试");
                mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        Log.d("z",mLocation.getLatitude()+"");
        try {
            jsonObject.put("status", "1000");
            JSONObject resultJson = new JSONObject();
            resultJson.put("latitude", mLocation.getLatitude());
            resultJson.put("Longitude", mLocation.getLongitude());
            jsonObject.put("data",resultJson);
            mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void getGpsBd() {
        if( !BaiduLocationUtils.getInstance(this).isLocationProviderEnabled()){
            Toast.makeText(MainActivity.this,"请先开启gps定位",Toast.LENGTH_LONG).show();
            return;
        }
        JSONObject jsonObject = new JSONObject();
        BDLocation mLocation = BaiduLocationUtils.getInstance(this).getLocation();
        if(mLocation == null){
            try {
                jsonObject.put("status", "9999");
                jsonObject.put("message", "获取定位失败，请稍后再试");
                mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        Log.d("z",mLocation.getLatitude()+"");
        try {
            jsonObject.put("status", "1000");
            JSONObject resultJson = new JSONObject();
            resultJson.put("latitude", mLocation.getLatitude());
            resultJson.put("Longitude", mLocation.getLongitude());
            jsonObject.put("data",resultJson);
            mMainPresenterCompl.callBackHandler(ConstantUils.JS_FUNCTION_LOCATION_FLAG, jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}
